package com.baixiaowen.xiaoaointerview.大厂笔试_白板面试篇.容器_集合_映射;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 顺序问题
 *
 * @author Baixiaowen
 */
public class HashSetvsTreeSet {

    public static void test_order() {
        HashSet hashset = new HashSet<Integer>();
        hashset.add(null);
        hashset.add(7);
        hashset.add(2);
        hashset.add(81);
        System.err.println(hashset.stream().map(x -> x.toString()).collect(Collectors.joining(",")));

        Integer x = 3;
        TreeSet<Integer> treeSet = new TreeSet<Integer>() {
            {
                add(3);
                add(7);
                add(2);
                add(81);
            }
        };

        Integer lower = treeSet.lower(x);
        Integer higher = treeSet.higher(x);
        System.err.println(lower);
        System.err.println(higher);

        Integer floor = treeSet.floor(x);
        Integer ceiling = treeSet.ceiling(x);
        System.err.println(floor);
        System.err.println(ceiling);

        System.err.println(treeSet.stream().map(o -> o.toString()).collect(Collectors.joining(",")));
    }

    public static void main(String[] args) {
//        test_order();
        testBenchmark();
    }

    /**
     * TreeSet 和 HashSet性能的比较
     */
    public static void testBenchmark() {
        Random random = new Random();

        LinkedList<String> words = new LinkedList<>();
        for (int i = 0; i < 1000_000; i++) {
            String word = random.ints(97, 123)
                    .limit(12)
                    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                    .toString();
            words.add(word);
        }

        // O(1)
        HashSet<String> hashSet = new HashSet<>();
        // o(logN)
        TreeSet<String> treeSet = new TreeSet<>();

        Long start = System.currentTimeMillis();
        for (String w : words) {
            hashSet.add(w);
        }
        for (String w : words) {
            hashSet.contains(w);
        }

        System.err.println("hashSet time : " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        for (String w : words) {
            treeSet.add(w);
        }
        for (String w : words) {
            treeSet.contains(w);
        }

        System.err.println("treeSet time : " + (System.currentTimeMillis() - start));


    }

}
